unit AuditLog;

interface
uses
  SysUtils;

type
  EOEventType     = (
    etNone,
    etError,
    etWarning,
    etInformation,
    etSuccessAudit,
    etFailureAudit,
    etException,
    etDUNIT
  );

  EOEventSource   = String;
  EOEventMessage  = String;
  EOEventUser     = String;

procedure EventLog(
    EventType: EOEventType;
    EventSource: EOEventSource;
    EventMessage: EOEventMessage;
    EventUser: EOEventUser = '';
    ThreadID: Longword = 0
  );

function ByteBufferToString(const Buffer; Count: Integer): String;

var
  AuditLogPath: String = '';

implementation
uses
  INI_Database, synchobj;

const
  MaxLogSize    = 1048576;

procedure EventLog(
    EventType: EOEventType;
    EventSource: EOEventSource;
    EventMessage: EOEventMessage;
    EventUser: EOEventUser = '';
    ThreadID: Longword = 0
  );

var
  tmpMutex: EOMutex;
  tmpF: TextFile;
  tmpBF: File;
  tmpFN, newFN: String;
  sizeFile: Longint;
  postfix: Integer;
begin
  if AuditLogPath = '' then
    AuditLogPath := INI_Database.getInstance.XLogPath;

  try
    tmpMutex := EOMutex.CreateMutex(Nil, False, 'EXPOSE75AuditLog');
    try
      if not tmpMutex.Lock then
        exit;

      tmpFN := AuditLogPath + FormatDateTime('yyyymmdd', Now) + 'Log.txt';

      if FileExists(tmpFN) then begin
        AssignFile(tmpBF, tmpFN);
        try
          Reset(tmpBF, 1);
          sizeFile := FileSize(tmpBF);
        finally
          CloseFile(tmpBF);
        end;

        if sizeFile >= MaxLogSize then begin
          postfix := 0;
          repeat
            postfix := postfix + 1;
            newFN := AuditLogPath + FormatDateTime('yyyymmdd_', Now) + Format('%4.4x', [postfix]) + 'Log.txt';
          until not FileExists(newFN);

          AssignFile(tmpBF, tmpFN);
          Rename(tmpBF, newFN); //FormatDateTime('yyyymmdd', Now) + Format('%4.4x', [postfix]) + 'Log.txt');

        end;

      end;

      AssignFile(tmpF, tmpFN);
      try
        if FileExists(tmpFN) then
          Append(tmpF)
        else
          ReWrite(tmpF);

        WriteLn(tmpF, Format('[%.2d] [%s] [%s] [%s] [%s] [%s] [%d]', [Integer(EventType), FormatDateTime('mmm-dd-yyyy hh:nn:ss:zzz', Now), EventSource, EventMessage, ParamStr(0), EventUser, ThreadID]));

        Flush(tmpF);
      finally
        CloseFile(tmpF);
      end;

    finally
      tmpMutex.Free;
    end;
  except
  end;
end;

function ByteBufferToString(const Buffer; Count: Integer): String;
var
  ctr: Integer;
begin
  try
    Result := '';

    for ctr := 1 to Count do begin
      Result := Result + Format('%2.2x ', [Integer(PChar(@Buffer)[ctr-1])]);
    end;
  except
    on E: Exception do begin
      EventLog(etException, 'ByteBufferToString', E.Message);
      raise
    end;
  end;
end;

end.
